from flask import Blueprint,jsonify,request
from conf.comm import sqlalchemy_context
from database import *
import json


# 实例化
bp_course = Blueprint('course',__name__)

# 无限极分类构造
def xtree(data):
    tree = {}
    list = []
    if data:
        # 解析成字典
        for i in data:
            tree[i['id']] = i
        for j in data:
            # 判断是否有父类,=0代表没有父类，直接加入列表
            if not j['parent']:
                list.append(j)
            else:
                # 有父类
                # 看一下父类下是否有子类，如果有，直接append，如果没有初始化
                if 'son' not in tree[j['parent']]:
                    tree[j['parent']]['son'] = []
                # 把子类加到特定的父类下
                tree[j['parent']]['son'].append(j)
        return list
    else:
        return data

# 添加分类
@bp_course.route('/cateM',methods=['POST','GET'])
@sqlalchemy_context()
def cateM():
    if request.method == "POST":
        # try:
            # 获取用户输入
            data = request.data
            if data:
                data = json.loads(data)
            else:
                data = request.form
            # 构造对象
            try:
                params = data['params']
            except:
                params = ''
            cate = Cate(name=data['name'],parent=data['parent'],level=data['level'],params=params)
            # 添加
            db.session.add(cate)
            # 提交
            db.session.commit()
            # 返回结果
            return jsonify({'code':200})
        # except:
        #     return jsonify({'code':10010})
    else:
        # 获取所有分类
        list=[]
        cates = Cate.query.all()
        if cates:
            for i in cates:
                dict={'id':i.id,'name':i.name,'parent':i.parent,'params':i.params,'level':i.level}
                list.append(dict)
        # 调用xtree方法重构数据
        list1 = xtree(list)
        return jsonify({'code':200,'list':list1})